import React, { useState, useEffect, useCallback, useMemo } from "react";

export const CallbackMemoDemo = () => {
  const [count, setCount] = useState(0)
  const [otherCount, setOtherCount] = useState(0)
  useEffect(() => {
    setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
    setInterval(() => {
      setOtherCount(otherCount => otherCount + 1)
    }, 3000)
  }, [])

  // 相当于缓存了方法
  const handleClick = useCallback(() => {
    console.log(count)
  }, [])
  console.log("更新")

  // 相当于监听了otherCount的变化,才重新计算
  const result = useMemo(() => {
    console.log('3秒更新一次')
    return otherCount * 2
  }, [otherCount])

  return (
    <div>
      一般计数: {count}
      <div>其它计数: {otherCount}</div>
      <div>合计: {result}</div>
      <button onClick={handleClick}>点击</button>

    </div>
  )
}